import {
  getFileList
} from '~/services/api/tool'

Page({
  /** 
   * 页面的初始数据 
   */
  data: {
    goodsListLoadStatus: 0,
    pageLoading: false,
    loadMoreStatus: 0,
    loading: true,
    fileList: [],
    kid: '',
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    userId: ''
  },
  goodListPagination: {
    pageNo: 1,
    pageSize: 10,
  },
  onLoad: function () {
    var that = this;
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    this.setData({
      kid: options.kid
    })
  },
  preview(e) {
    let item = e.currentTarget.dataset.item;
    var suffix = item.filePath.substring(item.filePath.lastIndexOf(".")); //.txt
    let fileType = suffix.split('.')[1];
    let url = item.filePath;
    if (!fileType || !url) {
      console.log("网络延迟，请稍后尝试")
      return
    }
    fileType = fileType.toLowerCase()
    if (['png', 'jpg', 'jpeg', 'gif'].includes(fileType)) {
      wx.previewImage({
        current: url,
        urls: [url],
        showmenu: true,
      })
    } else if (['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx'].includes(fileType)) {
      console.log(666, url)
      wx.showLoading({
        title: '打开中',
        icon: 'none'
      })
      wx.downloadFile({
        url: url,
        timeout: 300000,
        success(res) {
          wx.hideLoading()
          console.log(res, "--文件下载成功--")
          if (res.statusCode == 200) {
            let realPath = res.tempFilePath
            if (['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx'].includes(fileType)) {
              wx.openDocument({
                filePath: realPath,
                fileType: fileType,
                showMenu: true,
                success: function (res) {
                  console.log('打开文档成功')
                },
                fail(error) {
                  console.log(error, "文档打开失败")
                }
              })
            } else {
              wx.showToast({
                title: "文件格式不支持",
                icon: "none"
              })
            }
          }
        },
        fail(err) {
          wx.hideLoading()
          wx.showToast({
            title: "文件太大,请到pc端查看",
            icon: "error"
          })
          console.log(err, "下载失败")
        }
      })
    } else if (['mp4', 'm4v', '3gp'].includes(fileType)) {
      wx.previewMedia({
        sources: [{
          url: url,
          type: 'video'
        }],
        showmenu: true,
        fail(err) {
          console.log(err, "视频预览失败")
        }
      })
    }

  },

  onShow() {
    this.loadHomePage();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();
    this.setData({
      pageLoading: true,
    });
    this.loadGoodsList(true);
  },
  onPullDownRefresh() {
    this.loadHomePage();
  },
  onReTry() {
    this.loadGoodsList();
  },
  async loadGoodsList(fresh = false) {
    const role = wx.getStorageSync('role');
    const userId = role?.userId;
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
      this.setData({
        pageLoading: false,
      });
    }
    this.setData({
      goodsListLoadStatus: 1
    });
    const pageSize = this.goodListPagination.pageSize;
    let pageIndex = this.goodListPagination.pageNo + 1;
    if (fresh) {
      pageIndex = 1;
    }
    try {
      const {
        data
      } = await getFileList({
        "pageNo": pageIndex,
        "pageSize": pageSize,
        "param": {
          classifyId: this.data.kid
        }
      });
      this.setData({
        fileList: fresh ? data.entities : this.data.fileList.concat(data.entities),
        goodsListLoadStatus: data.entities.length > 1 ? 0 : 2,
      });

      this.goodListPagination.pageSize = data.pageSize;
      this.goodListPagination.pageNo = data.pageNo;
    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },

  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },

})